package com.smart.manager.wiki.entities.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import com.smart.common.entities.constant.ArcoTips;
import com.smart.common.entities.core.Page;
import com.smart.manager.wiki.entities.body.RDocEssay;
import com.smart.manager.wiki.entities.models.WikiDocEssay;
import com.smart.manager.wiki.entities.models.query.QWikiDocEssay;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author Administrator
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class DocEssayRepository {


    public Page<WikiDocEssay> pageList(RDocEssay.SearchBody search) {
        QWikiDocEssay query = new QWikiDocEssay();
        Opt.ofBlankAble(search.getTitle()).ifPresent(x -> query.title.contains(x));
        query.order().sort.asc().order().id.desc();
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<WikiDocEssay>().load(query.findPagedList());
    }

    public void add(RDocEssay.EditBody body) {
        BeanUtil.copyProperties(body, WikiDocEssay.class).setReadCount(0).save();
    }


    public void update(Long id, RDocEssay.EditBody body) {
        QWikiDocEssay query = new QWikiDocEssay();
        WikiDocEssay record = query.id.eq(id).setMaxRows(1).findOne();
        Assert.notNull(record, "修改失败:攻略数据不存在或已被删除");
        BeanUtil.copyProperties(body, record);
        Objects.requireNonNull(record).update();
    }

    public int delByIds(List<Long> ids) {
        List<WikiDocEssay> list = new QWikiDocEssay().id.in(ids).findList();
        Assert.notEmpty(list, ArcoTips.DELETE_NOT_FOUND);
        return DB.deleteAll(list);
    }


    /**
     * @param checkNull 是否检查空值
     * @param addCount  是否增加阅读次数
     * @param id 攻略ID
     * @return {@code WikiDocEssay}
     */
    public WikiDocEssay readOne(Long id, Boolean checkNull, boolean addCount) {
        WikiDocEssay strategyEssay = new QWikiDocEssay().id.eq(id).setMaxRows(1).findOne();
        Assert.notNull(strategyEssay, "攻略文件不存在");
        if (addCount) {
            strategyEssay.setReadCount(strategyEssay.getReadCount() + 1);
            strategyEssay.update();
        }
        return strategyEssay;

    }


}
